import { useState, useEffect } from 'react';
import { Button, Upload, message } from 'antd';
import { UserOutlined, PlusOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import { accountInfo, uploadAvatar } from '@/api/account';
import { serverUrl } from '@/utils/common';
import useUserStore from '@/stores/userStore';

const Center = () => {
  const [user, setUser] = useState({});
  const [loading, setLoading] = useState(false);
  const userStore = useUserStore(); 
  const user1 = JSON.parse(sessionStorage.getItem('user'));

  // 获取账号信息
  const getAccountInfo = async () => {
    try {
      const res = await accountInfo({ id: user1.id });
      setUser(res.accountInfo);
    } catch (error) {
      console.error('获取用户信息失败', error);
      message.error('获取用户信息失败');
    }
  };

  useEffect(() => {
    getAccountInfo();
  }, []);

  // 时间格式化
  const formatDate = (date) => {
    if (!date) return '';
    return dayjs(date).format('YYYY-MM-DD');
  };

  // 上传前检查
  const beforeUpload = (file) => {
    const isImage = file.type.includes('image');
    if (!isImage) {
      message.error('请上传图片文件');
      return false;
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error('图片大小不能超过 2MB');
      return false;
    }
    return true;
  };

  // 自定义上传
  const customUpload = async (options) => {
    const { file, onSuccess, onError } = options;
    try {
      setLoading(true);
      const formData = new FormData();
      formData.append('avatar', file);
      formData.append('id', user1.id);
      
      await uploadAvatar(formData);
      onSuccess();
      getAccountInfo();
      userStore.setUserInfoState(); // 修改为正确的方法名
      message.success('头像上传成功');
    } catch (error) {
      console.error('上传失败', error);
      onError();
      message.error('头像上传失败');
    } finally {
      setLoading(false);
    }
  };

  const editInfo = () => {
    message.info('编辑资料');
  };

  const changePwd = () => {
    message.info('修改密码');
  };

  return (
    <div className="simple-profile">
      <h2>个人中心</h2>
      
      <div className="profile-content">
        {/* 头像区域 */}
        <div className="avatar-box">
          <Upload
            name="avatar"
            listType="picture-circle"
            showUploadList={false}
            beforeUpload={beforeUpload}
            customRequest={customUpload}
            disabled={loading}
          >
            {user.imgUrl ? (
              <img 
                src={`${serverUrl}${user.imgUrl}`} 
                alt="avatar" 
                style={{ width: '100%', borderRadius: '50%' }}
              />
            ) : (
              <div>
                {loading ? <UserOutlined /> : <PlusOutlined />}
                <div style={{ marginTop: 8 }}>上传</div>
              </div>
            )}
          </Upload>
          <p>点击更换头像</p>
        </div>
        
        {/* 信息区域 */}
        <div className="info-box">
          <div className="info-item">
            <span>账号：</span>
            <span>{user.account}</span>
          </div>
          <div className="info-item">
            <span>用户组：</span>
            <span>{user.userGroup}</span>
          </div>
          <div className="info-item">
            <span>注册时间：</span>
            <span>{formatDate(user.ctime)}</span>
          </div>
          
          <div className="buttons">
            <Button type="primary" size="small" onClick={editInfo}>
              编辑资料
            </Button>
            <Button size="small" onClick={changePwd} style={{ marginLeft: 8 }}>
              修改密码
            </Button>
          </div>
        </div>
      </div>

      <style jsx>{`
        .simple-profile {
          max-width: 600px;
          margin: 20px auto;
          padding: 20px;
        }
        h2 {
          text-align: center;
          margin-bottom: 20px;
        }
        .profile-content {
          display: flex;
          gap: 30px;
          padding: 20px;
          background: #fff;
          border-radius: 8px;
          box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
        }
        .avatar-box {
          text-align: center;
        }
        .info-box {
          flex: 1;
        }
        .info-item {
          margin-bottom: 15px;
        }
        .info-item span:first-child {
          color: #666;
          margin-right: 10px;
        }
        .buttons {
          margin-top: 25px;
        }
        @media (max-width: 600px) {
          .profile-content {
            flex-direction: column;
            align-items: center;
          }
        }
      `}</style>
    </div>
  );
};

export default Center;